package com.ljy.my_study.leetcode.k个一组翻转链表;

import com.ljy.my_study.leetcode.k个一组翻转链表.TestMain.ListNode;

public class TestMain2 {

    public static void main(String[] args) {
        TestMain testMain=new TestMain();
        int[] arr= {5,4,2,7,12,3,68,12,21,87,9,19};
        int[] arr1= {1,2};
        int[] arr2= {1,2,3,4,5};
        int[] arr3= {1,2};

        ListNode head=testMain.createListNodeKGroup(arr2);
        testMain.printKGroup(head);
        head=new TestMain2().reverseKGroup(head, 3);
        testMain.printKGroup(head);
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode result=null;
        ListNode preNode=null;
        ListNode node=head;
        ListNode next=node.next;
        boolean isFirst=true;
        while(node!=null){
            Stack stack=new Stack();
            for(int count=0;count<k;count++){
                stack.add(node);
                node=next;
                if(next==null){
                    break;
                }
                next=next.next;
            }
            if(isFirst){
                result=stack.getNewFirstNode();
                preNode=stack.getNewLastNode();
                isFirst=false;
            }else{
                preNode.next=stack.getNewFirstNode();
                preNode=stack.getNewLastNode();
            }
        }

        return result;
    }

    public class Stack{

        ListNode last;
        ListNode first;

        public void add(ListNode node){
            node.next=null;
            if(last!=null){
                node.next=last;
                last=node;
            }else{
                first=last=node;
            }
        }

        public ListNode getNewLastNode(){
            return first;
        }

        public ListNode getNewFirstNode(){
            return last;
        }
    }
}
